package com.example.test.filelock;

import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @Author: fxy
 * @Date: 2022/01/12/9:19
 * @Description:
 */
public class Demo1 {
    public static void main(String[] args) throws Exception {
        String input = "atguigu";
        System.out.println("input"+input);
        ByteBuffer buffer = ByteBuffer.wrap(input.getBytes());

        String filePath = "D:\\project\\myproject\\test\\test07-nio\\src\\main\\resources\\file\\01.txt";
        Path path = Paths.get(filePath);

        FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE,StandardOpenOption.APPEND);
        channel.position(channel.size()-1);
        FileLock lock = channel.lock();
        System.out.println(lock.isShared());
        channel.write(buffer);
        channel.close();
        readFile(filePath);
    }

    private static void readFile(String filePath) throws Exception {
        FileReader fileReader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String tr = bufferedReader.readLine();
        while(tr!=null){
            System.out.println(" "+tr);
            tr = bufferedReader.readLine();
        }
        fileReader.close();
        bufferedReader.close();
    }
}
